#!/bin/bash
#
# live: Init script for live image
#
# chkconfig: 345 00 99
# description: Init script for live image.

. /etc/init.d/functions

if ! strstr "`cat /proc/cmdline`" liveimg || [ "$1" != "start" ]; then
    exit 0
fi

if [ -e /.liveimg-configured ] ; then
    configdone=1
fi


exists() {
    which $1 >/dev/null 2>&1 || return
    $*
}

touch /.liveimg-configured

# mount live image
if [ -b `readlink -f /dev/live` ]; then
   mkdir -p /mnt/live
   mount -o ro /dev/live /mnt/live 2>/dev/null || mount /dev/live /mnt/live
fi

livedir="LiveOS"
for arg in `cat /proc/cmdline` ; do
  if [ "${arg##live_dir=}" != "${arg}" ]; then
    livedir=${arg##live_dir=}
    return
  fi
done

# enable swaps unless requested otherwise
swaps=`blkid -t TYPE=swap -o device`
if ! strstr "`cat /proc/cmdline`" noswap && [ -n "$swaps" ] ; then
  for s in $swaps ; do
    action "Enabling swap partition $s" swapon $s
  done
fi
if ! strstr "`cat /proc/cmdline`" noswap && [ -f /mnt/live/${livedir}/swap.img ] ; then
  action "Enabling swap file" swapon /mnt/live/${livedir}/swap.img
fi

mountPersistentHome() {
  # support label/uuid
  if [ "${homedev##LABEL=}" != "${homedev}" -o "${homedev##UUID=}" != "${homedev}" ]; then
    homedev=`/sbin/blkid -o device -t "$homedev"`
  fi

  # if we're given a file rather than a blockdev, loopback it
  if [ "${homedev##mtd}" != "${homedev}" ]; then
    # mtd devs don't have a block device but get magic-mounted with -t jffs2
    mountopts="-t jffs2"
  elif [ ! -b "$homedev" ]; then
    loopdev=`losetup -f`
    if [ "${homedev##/mnt/live}" != "${homedev}" ]; then
      action "Remounting live store r/w" mount -o remount,rw /mnt/live
    fi
    losetup $loopdev $homedev
    homedev=$loopdev
  fi

  # if it's encrypted, we need to unlock it
  if [ "$(/sbin/blkid -s TYPE -o value $homedev 2>/dev/null)" = "crypto_LUKS" ]; then
    echo
    echo "Setting up encrypted /home device"
    plymouth ask-for-password --command="cryptsetup luksOpen $homedev EncHome"
    homedev=/dev/mapper/EncHome
  fi

  # and finally do the mount
  mount $mountopts $homedev /home
  # if we have /home under what's passed for persistent home, then
  # we should make that the real /home.  useful for mtd device on olpc
  if [ -d /home/home ]; then mount --bind /home/home /home ; fi
  [ -x /sbin/restorecon ] && /sbin/restorecon /home
  if [ -d /home/$LIVECD_USER ]; then USERADDARGS="-M" ; fi
}

findPersistentHome() {
  for arg in `cat /proc/cmdline` ; do
    if [ "${arg##persistenthome=}" != "${arg}" ]; then
      homedev=${arg##persistenthome=}
      return
    fi
  done
}

if strstr "`cat /proc/cmdline`" persistenthome= ; then
  findPersistentHome
elif [ -e /mnt/live/${livedir}/home.img ]; then
  homedev=/mnt/live/${livedir}/home.img
fi

# if we have a persistent /home, then we want to go ahead and mount it
if ! strstr "`cat /proc/cmdline`" nopersistenthome && [ -n "$homedev" ] ; then
  action "Mounting persistent /home" mountPersistentHome
fi

# make it so that we don't do writing to the overlay for things which
# are just tmpdirs/caches
mount -t tmpfs -o mode=0755 varcacheyum /var/cache/yum
mount -t tmpfs tmp /tmp
mount -t tmpfs vartmp /var/tmp
[ -x /sbin/restorecon ] && /sbin/restorecon /var/cache/yum /tmp /var/tmp >/dev/null 2>&1

if [ -n "$configdone" ]; then
  exit 0
fi


## fix various bugs and issues
# unmute sound card
exists alsaunmute 0 2> /dev/null

# turn off firstboot for livecd boots
echo "RUN_FIRSTBOOT=NO" > /etc/sysconfig/firstboot

# turn off mdmonitor by default
chkconfig --level 345 mdmonitor       off 2>/dev/null

# turn off setroubleshoot on the live image to preserve resources
chkconfig --level 345 setroubleshoot  off 2>/dev/null

# don't start cron/at as they tend to spawn things which are
# disk intensive that are painful on a live image
chkconfig --level 345 auditd          off 2>/dev/null
chkconfig --level 345 crond           off 2>/dev/null
chkconfig --level 345 atd             off 2>/dev/null
chkconfig --level 345 readahead_early off 2>/dev/null
chkconfig --level 345 readahead_later off 2>/dev/null

# disable kdump service
chkconfig --level 345 kdump           off 2>/dev/null

# disable microcode_ctl service
chkconfig --level 345 microcode_ctl   off 2>/dev/null

# disable smart card services
chkconfig --level 345 openct          off 2>/dev/null
chkconfig --level 345 pcscd           off 2>/dev/null

# disable postfix service
chkconfig --level 345 postfix         off 2>/dev/null

# Stopgap fix for RH #217966; should be fixed in HAL instead
touch /media/.hal-mtab

# workaround clock syncing on shutdown that we don't want (#297421)
sed -i -e 's/hwclock/no-such-hwclock/g' /etc/rc.d/init.d/halt

# set the LiveCD hostname
sed -i -e 's/HOSTNAME=localhost.localdomain/HOSTNAME=livedvd.centos/g' /etc/sysconfig/network
/bin/hostname livedvd.centos

## create the LiveCD default user
# add default user with no password
/usr/sbin/useradd -c "LiveCD default user" centoslive
/usr/bin/passwd -d centoslive > /dev/null
# give default user sudo privileges
echo "centoslive     ALL=(ALL)     NOPASSWD: ALL" >> /etc/sudoers

## configure default user's desktop
# set up timed auto-login at 10 seconds
cat >> /etc/gdm/custom.conf << FOE
[daemon]
TimedLoginEnable=true
TimedLogin=centoslive
TimedLoginDelay=10
FOE

# add keyboard and display configuration utilities to the desktop
mkdir -p /home/centoslive/Desktop >/dev/null
cp /usr/share/applications/gnome-keyboard.desktop           /home/centoslive/Desktop/
cp /usr/share/applications/gnome-display-properties.desktop /home/centoslive/Desktop/

# disable screensaver locking
gconftool-2 --direct --config-source=xml:readwrite:/etc/gconf/gconf.xml.defaults -s -t bool   /apps/gnome-screensaver/lock_enabled "false" >/dev/null

# disable PackageKit update checking by default
gconftool-2 --direct --config-source=xml:readwrite:/etc/gconf/gconf.xml.defaults -s -t int /apps/gnome-packagekit/update-icon/frequency_get_updates "0" >/dev/null

# Switching to Thunderbird as the default MUA
gconftool-2 --direct --config-source=xml:readwrite:/etc/gconf/gconf.xml.defaults --type string --set /desktop/gnome/url-handlers/mailto/command "thunderbird %" >/dev/null


# detecting disk partitions and logical volumes 
CreateDesktopIconHD()
{
cat > /home/centoslive/Desktop/Local\ hard\ drives.desktop << EOF_HDicon
[Desktop Entry]
Encoding=UTF-8
Version=1.0
Type=Link
Name=Local hard drives
Name[en_US]=Local hard drives
Name[fr_CA]=Disques durs locaux
URL=/mnt/disc
Icon=/usr/share/icons/gnome/32x32/devices/gnome-dev-harddisk.png
EOF_HDicon

chmod 755 /home/centoslive/Desktop/Local\ hard\ drives.desktop
}

CreateDesktopIconLVM()
{
mkdir -p /home/centoslive/Desktop >/dev/null

cat > /home/centoslive/Desktop/Local\ logical\ volumes.desktop << EOF_LVMicon
[Desktop Entry]
Encoding=UTF-8
Version=1.0
Type=Link
Name=Local logical volumes
Name[en_US]=Local logical volumes
Name[fr_CA]=Volumes logiques locaux
URL=/mnt/lvm
Icon=/usr/share/icons/gnome/32x32/devices/gnome-dev-harddisk.png
EOF_LVMicon

chmod 755 /home/centoslive/Desktop/Local\ logical\ volumes.desktop
}

# don't mount disk partitions if 'nodiskmount' is given as a boot option
if ! strstr "`cat /proc/cmdline`" nodiskmount ; then
	MOUNTOPTION="ro"
	HARD_DISKS=`egrep "[sh]d.$" /proc/partitions | tr -s ' ' | sed 's/^  *//' | cut -d' ' -f4`

	echo "Mounting hard disk partitions... "
	for DISK in $HARD_DISKS; do
	    # Get the device and system info from fdisk (but only for fat and linux partitions).
	    FDISK_INFO=`fdisk -l /dev/$DISK | tr [A-Z] [a-z] | egrep "fat|linux" | egrep -v "swap|extended|lvm" | sed 's/*//' | tr -s ' ' | tr ' ' ':' | cut -d':' -f1,6-`
	    for FDISK_ENTRY in $FDISK_INFO; do
		PARTITION=`echo $FDISK_ENTRY | cut -d':' -f1`
		MOUNTPOINT="/mnt/disc/${PARTITION##/dev/}"
		mkdir -p $MOUNTPOINT
		MOUNTED=FALSE

		# get the partition type
		case `echo $FDISK_ENTRY | cut -d':' -f2-` in
		*fat*) 
		    FSTYPES="vfat"
		    EXTRAOPTIONS=",uid=500";;
		*)
		    FSTYPES="ext4 ext3 ext2"
		    EXTRAOPTIONS="";;
		esac

		# try to mount the partition
		for FSTYPE in $FSTYPES; do
		    if mount -o "${MOUNTOPTION}${EXTRAOPTIONS}" -t $FSTYPE $PARTITION $MOUNTPOINT &>/dev/null; then
			echo "$PARTITION $MOUNTPOINT $FSTYPE noauto,${MOUNTOPTION}${EXTRAOPTIONS} 0 0" >> /etc/fstab
			echo -n "$PARTITION "
			MOUNTED=TRUE
			CreateDesktopIconHD
		    fi
		done
		[ $MOUNTED = "FALSE" ] && rmdir $MOUNTPOINT
	    done
	done
	echo
fi

# don't mount logical volumes if 'nolvmmount' is given as a boot option
if ! strstr "`cat /proc/cmdline`" nolvmmount ; then
        MOUNTOPTION="ro"
	FSTYPES="ext4 ext3 ext2"
	echo "Scanning for logical volumes..."
	if ! lvm vgscan 2>&1 | grep "No volume groups"; then
	    echo "Activating logical volumes ..."
	    modprobe dm_mod >/dev/null
	    lvm vgchange -ay
	    LOGICAL_VOLUMES=`lvm lvdisplay -c | sed "s/^  *//" | cut -d: -f1`
	    if [ ! -z "$LOGICAL_VOLUMES" ]; then
		echo "Making device nodes ..."
		lvm vgmknodes
		echo -n "Mounting logical volumes ... "
		for VOLUME_NAME in $LOGICAL_VOLUMES; do
		    VG_NAME=`echo $VOLUME_NAME | cut -d/ -f3`
		    LV_NAME=`echo $VOLUME_NAME | cut -d/ -f4`
		    MOUNTPOINT="/mnt/lvm/${VG_NAME}-${LV_NAME}"
		    mkdir -p $MOUNTPOINT

		    MOUNTED=FALSE
		    for FSTYPE in $FSTYPES; do
			if mount -o $MOUNTOPTION -t $FSTYPE $VOLUME_NAME $MOUNTPOINT &>/dev/null; then
			    echo "$VOLUME_NAME $MOUNTPOINT $FSTYPE defaults,${MOUNTOPTION} 0 0" >> /etc/fstab
			    echo -n "$VOLUME_NAME "
			    MOUNTED=TRUE
			    CreateDesktopIconLVM
			    break
			fi
		    done
		    [ $MOUNTED = FALSE ] && rmdir $MOUNTPOINT
		done
		echo

	    else
		echo "No logical volumes found"
	    fi
	fi
fi

# give back ownership to the default user
chown -R centoslive:centoslive /home/centoslive
